﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WQLWebAPI.Api.Filters;
using WQLWebAPI.Api.Models;
using WQLWebAPI.Application.Images;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WQLWebAPI.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImagesController : BaseApiController
    {
        private readonly IImageService _imageService;
        public ImagesController(IImageService imageService)
        {
            _imageService = imageService;
        }

        [HttpGet("{id}")]
        //[Logger(Operation = "根据id获取图片")]
        public async Task<ActionResult> Get(int id)
        {
            var infos = await _imageService.GetAsync(id);
            if (infos != null)
            {
                return File(infos.ImageInfo, "image/jpeg");
            }
            return NoContent();
            //return Ok(result);
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="ids">图片id集合</param>
        /// <returns></returns>
        [HttpPost]
        //[PermissionAuthorzize(Area = AuthorizeClaims.图片, Permission = AuthorizeClaims.删除)]
        //[Logger(Operation = "删除图片")]
        public async Task<ActionResult> Delete(List<int> ids)
        {
            var result = await _imageService.RemovesAsync(ids);
            return ResultResponse(result, "删除图片");
        }
        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>

        [HttpPost, Route("PostFile")]
        //[Logger(Operation = "创建图片")]
        //[PermissionAuthorzize(Area = AuthorizeClaims.图片, Permission = AuthorizeClaims.创建)]
        public async Task<ActionResult> PostFile(IFormFile image)
        {
            if (image.ContentType.Contains("image"))
            {
                var stream = image.OpenReadStream();
                byte[] bytes = new byte[stream.Length];

                stream.Read(bytes, 0, bytes.Length);

                // 设置当前流的位置为流的开始 
                stream.Seek(0, SeekOrigin.Begin);

                var result = await _imageService.CreateAsync(bytes);
                return Ok(new { info = @"api/Images/" + result.Id });
            }
            else
            {
                return BadRequest("上传正确格式的图片");
            }

        }
    }
}